import { ApiResponse, LoginForm, Token } from '../../types/data'
import { LoginAction, RootThunkAction } from '../../types/store'
import axios from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage'
/**
 * 无感刷新 存储最新的token
 * @param params
 * @returns
 */
export function saveToken(params: Token): LoginAction {
  setToken(params)
  return {
    type: 'login/login',
    payload: params,
  }
}
export function login(values: LoginForm): RootThunkAction {
  return async (dispatch) => {
    // const res = await axios.post<ApiResponse<Token>>('/authorizations', values)
    const res = await axios.request<ApiResponse<Token>>({
      method: 'post',
      url: '/authorizations',
      data: values,
    })
    // dispatch({
    //   type: 'login/login',
    //   payload: res.data.data,
    // })
    // setToken(res.data.data)
    // console.log(res.data.data)
    dispatch(saveToken(res.data.data))
  }
}
/**
 * 提供手机号发行验证码
 * @param mobile
 * @returns
 */
export function send(mobile: string) {
  return async () => {
    await axios.get(`/sms/codes/${mobile}`)
  }
}

/**
 * 退出系统
 * @returns
 */
export function logout(): LoginAction {
  // 清除本地token
  removeToken()
  return {
    type: 'login/logout',
  }
}
